/* Setup blank page controller */
(function () {
    'use strict';
    angular.module('module.record-system')
        .controller('RecordSystemController', RecordSystemController)
        .filter('protectLevelFilter',protectLevelFilter)
        .filter('systemStateFilter',systemStateFilter);

    RecordSystemController.$inject = ['$rootScope', '$scope','i18nService','$uibModal'];

    function RecordSystemController($rootScope, $scope,i18nService,$uibModal) {
        var vm = this;

        vm.retrieveAllRecordSystem = retrieveAllRecordSystem; //查询所有信息系统信息

        vm.preCreateRecordSystem = preCreateRecordSystem;//新增信息系统信息

        vm.preUpdateRecordSystem = preUpdateRecordSystem;//编辑信息系统信息

        vm.preDetailRecordSystem = preDetailRecordSystem;//查看信息系统信息

        vm.preDetailRecordUnit = preDetailRecordUnit;//查看单位信息详情

        vm.preDetailRecordAuditLog = preDetailRecordAuditLog;//查看审核记录详情

        vm.preChangeRecordLog = preChangeRecordLog;//查看变更记录详情

        vm.preDeleteRecordSystem = preDeleteRecordSystem; //删除信息系统信息

        vm.preChangeRecordSystem = preChangeRecordSystem; //变更信息系统信息

        vm.preAbandonRecordSystem = preAbandonRecordSystem; //废弃信息系统信息

        vm.preRemovalSystem = preRemovalSystem; //迁移信息系统信息
        
        vm.openDownExportTemplate = openDownExportTemplate; //导出excel

        vm.selected=[];

        vm.getSelected = getSelected;

        /**
         * @description 中文支持
         */
        i18nService.setCurrentLang('zh-cn');


        /**
         * @description 页面列表信息处理
         * @type {{multiSelect: boolean, enableRowSelection: boolean, enableRowHeaderSelection: boolean, enableGridMenu: boolean, enableFullRowSelection: boolean, modifierKeysToMultiSelect: boolean, paginationPageSize: number, enableColumnResizing: boolean, paginationPageSizes: [number,number,number]}}
         */
        vm.gridOptions = {
            multiSelect: true,                                           //多选
            enableRowSelection: true,                                  //允许选中行
            enableRowHeaderSelection: false,                           //允许通过点击行首选中行
            enableGridMenu: true,
            enableFullRowSelection: true,                              //允许通过点击行任意位置选中行
            modifierKeysToMultiSelect: true,                           //只允许通过键盘辅助多选(前提是允许多选)
            paginationPageSize: 10,
            enableColumnResizing: true,
            paginationPageSizes: [10, 20, 50]
        };
        vm.gridOptions.onRegisterApi = onRegisterApi;
        vm.gridOptions.columnDefs = [
            { field: 'ID', visible: false, name: 'ID',  pinnedLeft:true},
            { field: 'SYSTEM_NAME', name: '信息系统名称', cellTooltip: true, headerTooltip: true},
            { field: 'RECORD_CODE', visible: true, name: '备案证明编号',  pinnedLeft:true, width: '160', cellTooltip: true, headerTooltip: true},
            { field: 'SYSTEM_LEVEL', visible: true, name: '安全保护等级', cellFilter:'protectLevelFilter', pinnedLeft:true,cellTooltip: true, width: '112', headerTooltip: true},
            { field: 'UNIT_NAME', visible: true, name: '单位名称',  pinnedLeft:true,cellTooltip: true, headerTooltip: true},
            { field: 'SERVICE_DATE', cellTooltip: true, visible: true, name: '何时投入使用',  pinnedLeft:true,cellFilter: 'date:"yyyy-MM-dd"', width: '150'},
            { field: 'SYSTEM_STATE', cellTooltip: true, visible: true, name: '状态', cellFilter:'systemStateFilter',  pinnedLeft:true, width: '80'}
        ];
        activate();

        return vm;

        function activate(){
            $scope.$on('$viewContentLoaded', function() {
                App.initAjax(); // initialize core components
            });

            // set sidebar closed and body solid layout mode
            $rootScope.settings.layout.pageContentWhite = true;
            $rootScope.settings.layout.pageBodySolid = false;
            $rootScope.settings.layout.pageSidebarClosed = false;
            retrieveAllRecordSystem();

        }

        function onRegisterApi(gridApi) {
            //set gridApi on scope
            vm.gridApi = gridApi;
        }

        /**
         * @description 新增信息系统信息
         */
        function preCreateRecordSystem(){
            var modalInstancere = $uibModal.open({
                animation: true,
                ariaLabelledBy: 'modal-title',
                ariaDescribedBy: 'modal-body',
                templateUrl: 'create.html',
                controller: 'RecordSystemCreateController',
                controllerAs: 'recordSystemCreate',
                size: 'lg'
            });
            modalInstancere.result.then(function () {

            }, function () {

            });
        }

        /**
         * @description 编辑信息系统信息
         */
        function preUpdateRecordSystem(){
            vm.selected = getSelected();
            if(vm.selected.length !== 1){
                swal('请选择一条待编辑的记录！');
            } else {
                var modalInstancere = $uibModal.open({
                    animation: true,
                    ariaLabelledBy: 'modal-title',
                    ariaDescribedBy: 'modal-body',
                    templateUrl: 'update.html',
                    controller: 'RecordSystemUpdateController',
                    controllerAs: 'recordSystemUpdate',
                    size: 'lg'
                });
                modalInstancere.result.then(function () {
                    retrieveAllRecordSystem();
                    vm.selected = [];//清空已选中的记录
                }, function () {
                    retrieveAllRecordSystem();
                    vm.selected = [];//清空已选中的记录
                });
            }
        }

        /**
         * @description 查看信息系统信息
         */
        function preDetailRecordSystem(){
            vm.selected = getSelected();
            if(vm.selected.length !== 1){
                swal('请选择一条待查看的记录！');
            } else {
                var modalInstancere = $uibModal.open({
                    animation: true,
                    ariaLabelledBy: 'modal-title',
                    ariaDescribedBy: 'modal-body',
                    templateUrl: 'systemView.html',
                    controller: 'RecordSystemSystemDetailController',
                    controllerAs: 'recordSystemSystemDetail',
                    size: 'lg'
                });
                modalInstancere.result.then(function () {
                    retrieveAllRecordSystem();
                    vm.selected = [];//清空已选中的记录
                }, function () {
                    retrieveAllRecordSystem();
                    vm.selected = [];//清空已选中的记录
                });
            }
        }


        function preDetailRecordAuditLog(){
            vm.selected = getSelected();
            if(vm.selected.length !== 1){
                swal('请选择一条待查看的记录！');
            } else {
                var modalInstancere = $uibModal.open({
                    animation: true,
                    ariaLabelledBy: 'modal-title',
                    ariaDescribedBy: 'modal-body',
                    templateUrl: 'auditLog.html',
                    controller: 'RecordSystemAuditLogController',
                    controllerAs: 'recordSystemAuditLog',
                    size: 'lg'
                });
                modalInstancere.result.then(function () {
                    retrieveAllRecordSystem();
                    vm.selected = [];//清空已选中的记录
                }, function () {
                    retrieveAllRecordSystem();
                    vm.selected = [];//清空已选中的记录
                });
            }
        }

        function preChangeRecordLog(){
            vm.selected = getSelected();
            if(vm.selected.length !== 1){
                swal('请选择一条待查看的记录！');
            } else {
                var modalInstancere = $uibModal.open({
                    animation: true,
                    ariaLabelledBy: 'modal-title',
                    ariaDescribedBy: 'modal-body',
                    templateUrl: 'changeLog.html',
                    controller: 'ChangeRecordLogController',
                    controllerAs: 'changeRecordLog',
                    size: 'lg'
                });
                modalInstancere.result.then(function () {
                    retrieveAllRecordSystem();
                    vm.selected = [];//清空已选中的记录
                }, function () {
                    retrieveAllRecordSystem();
                    vm.selected = [];//清空已选中的记录
                });
            }
        }
        /**
         * @description 查看单位信息详情
         */
        function preDetailRecordUnit(){
            vm.selected = getSelected();
            if(vm.selected.length !== 1){
                swal('请选择一条查看的记录！');
            } else {
                var modalInstancere = $uibModal.open({
                    animation: true,
                    ariaLabelledBy: 'modal-title',
                    ariaDescribedBy: 'modal-body',
                    templateUrl: 'unitDetail.html',
                    controller: 'RecordSystemUnitDetailController',
                    controllerAs: 'recordSystemUnitDetail',
                    size: 'lg'
                });
                modalInstancere.result.then(function () {
                    retrieveAllRecordSystem();
                    vm.selected = [];//清空已选中的记录
                }, function () {
                    retrieveAllRecordSystem();
                    vm.selected = [];//清空已选中的记录
                });
            }
        }

        /**
         * @description 删除信息系统信息
         */
        function preDeleteRecordSystem(){
            vm.selected = getSelected();
            if(vm.selected.length !== 1){
                swal('请选择一条待删除的记录！');
            } else {
                swal({
                    title: '确认删除备案系统信息?',
                    type: 'info',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: '确认!',
                    cancelButtonText: '取消!',
                    confirmButtonClass: 'btn btn-success margin-right-10',
                    cancelButtonClass: 'btn btn-primary',
                    buttonsStyling: false
                }).then(function () {
                    swal({
                        title: '提示！',
                        text: '删除成功!',
                        closeOnConfirm: true,
                        type: 'success'
                    }).then(function(){
                        retrieveAllRecordSystem();
                        vm.selected = [];//清空已选中的记录
                    });
                });
                retrieveAllRecordSystem();
            }
        }

        /**
         * @description 变更信息系统信息
         */
        function preChangeRecordSystem(){
            vm.selected = getSelected();
            if(vm.selected.length !== 1){
                swal('请选择一条待变更的记录！');
            } else {
                var modalInstancere = $uibModal.open({
                    animation: true,
                    ariaLabelledBy: 'modal-title',
                    ariaDescribedBy: 'modal-body',
                    templateUrl: 'change.html',
                    controller: 'RecordSystemChangeController',
                    controllerAs: 'recordSystemChange',
                    size: 'lg'
                });
                modalInstancere.result.then(function () {
                    retrieveAllRecordSystem();
                    vm.selected = [];//清空已选中的记录
                }, function () {
                    retrieveAllRecordSystem();
                    vm.selected = [];//清空已选中的记录
                });
            }
        }

        /**
         * @description 废弃信息系统信息
         */
        function preAbandonRecordSystem(){
            vm.selected = getSelected();
            if(vm.selected.length !== 1){
                swal('请选择一条待废弃的记录！');
            } else {
                swal({
                    title: '确认废弃备案系统信息?',
                    type: 'info',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: '确认!',
                    cancelButtonText: '取消!',
                    confirmButtonClass: 'btn btn-success margin-right-10',
                    cancelButtonClass: 'btn btn-primary',
                    buttonsStyling: false
                }).then(function () {
                    swal({
                        title: '提示！',
                        text: '操作成功!',
                        closeOnConfirm: true,
                        type: 'success'
                    }).then(function(){
                        retrieveAllRecordSystem();
                        vm.selected = [];//清空已选中的记录
                    });
                });
                retrieveAllRecordSystem();
            }
        }

        /**
         * @description 迁移信息系统信息
         */
        function preRemovalSystem(){

        }

        /**
         * @description 下载到本地文件 导出excel
         */
        function openDownExportTemplate(row) {
            console.log('保存到本地');
            /*var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL;
            if(urlCreator) {
                // Try to use a download link
                var link = document.createElement('a');
                if ('download' in link) {
                    // Try to simulate a click
                    try {
                        // Prepare a blob URL
                        console.log('Trying download link method with simulated click ...');
                        var blob = new Blob(['存放到本地测试'],{type:'word/plain'});
                        console.log(blob);
                        var url = urlCreator.createObjectURL(blob);
                        link.setAttribute('href', url);
                        // Set the download attribute (Supported in Chrome 14+ / Firefox 20+)
                        link.setAttribute('download', 'test.txt');
                        // Simulate clicking the download link
                        var event = document.createEvent('MouseEvents');
                        event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
                        link.dispatchEvent(event);
                        console.log('Download link method with simulated click succeeded');

                    } catch (ex) {
                        console.log('Download link method with simulated click failed with the following exception:');
                        console.log(ex);
                    }
                }
            }*/
        }


        /**
         * 备案证明编号规则：6位受理机关代码+2位行业类别+3位顺序号+短横线（-）+2位年度+3位顺序号
         */
        function retrieveAllRecordSystem(){
            var data =[
                {
                    'ID': '123',
                    'SYSTEM_NAME': '信息系统1',
                    'RECORD_CODE': '01000022001-17011',
                    'SYSTEM_LEVEL': '3',
                    'UNIT_NAME': 'XX单位1',
                    'SERVICE_DATE':'2017-10-24 00:00:00',
                    'SYSTEM_STATE':'1'
                },
                {
                    'ID': '8458454',
                    'SYSTEM_NAME': '信息系统2',
                    'RECORD_CODE': '01000023001-17001',
                    'SYSTEM_LEVEL': '4',
                    'UNIT_NAME': 'XX单位2',
                    'SERVICE_DATE':'2017-10-14 00:00:00',
                    'SYSTEM_STATE':'1'
                },{
                    'ID': '8458454ass',
                    'SYSTEM_NAME': '信息系统3',
                    'RECORD_CODE': '01000024001-17012',
                    'SYSTEM_LEVEL': '2',
                    'UNIT_NAME': 'XX单位3',
                    'SERVICE_DATE':'2017-10-04 00:00:00',
                    'SYSTEM_STATE':'2'
                }];
            vm.gridOptions.data = data;
        }
        /**
         * 获取选中记录的id
         * @returns {Array}
         */
        function getSelected(){
            var arr = vm.gridApi.selection.getSelectedRows();
            var selections = [];
            arr.forEach(function(e){
                selections.push(e.CBOX_INFO_GUID);
            });
            return selections;
        }

    }
    /**
     * @description 等级保护级别
     * @returns {Function}
     */
    function protectLevelFilter() {
        var relationHash = {
            1: '一级',
            2: '二级',
            3: '三级',
            4: '四级',
            5: '五级'
        };
        return function(input) {
            if (!input){
                return '';
            } else {
                return relationHash[input];
            }
        };

    }

    function systemStateFilter(){
        var relationHash = {
            1: '已备案',
            2: '已废弃'
        };
        return function(input) {
            if (!input){
                return '';
            } else {
                return relationHash[input];
            }
        };
    }
})();
